import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2023-05-09
 * Time: 10:12
 */

// 任务类
class MyTimerTask implements Comparable<MyTimerTask> {
    public Runnable runnable;
    public long time;
    public MyTimerTask(Runnable runnable,long delay) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis()+delay; // 绝对时间戳
    }

    // 比较方式
    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time-o.time);
    }

}

public class MyTimer {
    // 关键数据结构：优先级队列
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();

    // 创建锁对象
    Object locker = new Object();

    // 安排任务的方法
    public void schedule(Runnable Mytask,long time) {
        synchronized (locker) {
            MyTimerTask myTimerTask = new MyTimerTask(Mytask,time);
            queue.offer(myTimerTask);
            locker.notify();
        }
    }

    // 定时器中的工作线程负责执行定时任务
    public MyTimer() {
        Thread work = new Thread(()->{
            while (true) {
                synchronized (locker) {
                    while (queue.isEmpty()) {
                        try {
                            locker.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    MyTimerTask task = queue.peek();
                    long curTIme = System.currentTimeMillis();
                    if (curTIme>= task.time) {
                        queue.poll();
                        task.runnable.run();
                    } else {
                        try {
                            locker.wait(task.time - curTIme);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
        });
        work.start();
    }


}
